package com.xiangshizhineng.tianzhangzhi.app.scheduler;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiangshizhineng.tianzhangzhi.app.config.WebSocketServerEndpoint;
import com.xiangshizhineng.tianzhangzhi.app.model.entity.TzMes;
import com.xiangshizhineng.tianzhangzhi.app.model.response.TaskResponse;
import com.xiangshizhineng.tianzhangzhi.app.model.response.UserResponse;
import com.xiangshizhineng.tianzhangzhi.app.service.MesService;
import com.xiangshizhineng.tianzhangzhi.app.service.TaskService;
import com.xiangshizhineng.tianzhangzhi.app.service.UserService;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@ApiModel(description = "定时任务类")
@Component
public class Scheduler {

    @Autowired
    TaskService taskService;

    @Autowired
    UserService userService;

    @Autowired
    MesService mesService;

    @Autowired
    WebSocketServerEndpoint webSocketServerEndpoint;

    /**
     * 周五提醒未完成地块巡查的用户
     */
    @Scheduled(cron = "0 0 9 ? * FRI")
//    @Scheduled(cron = "*/30 * * * * ?")
    public void mesFRI(){
        List<TaskResponse> taskList = taskService.list(new QueryWrapper<TaskResponse>().select("distinct id","task_xcr","xzqhdm").eq("task_status_id","19"));
        List<String> xzqhdmList = new ArrayList<>();
        taskList.stream().forEach(t->{
            xzqhdmList.add(t.getXzqhdm());
        });
        List<UserResponse> user= userService.list(new QueryWrapper<UserResponse>().select("id").in("xzqdm",xzqhdmList));
        if(user!=null && user.size()>0){
            user.stream().forEach(u->{
            System.out.println("您负责的地块还有任务未巡查,您的用户id是'"+u.getId()+"'");
            String us = JSONObject.toJSONString(u);
                webSocketServerEndpoint.onMessage(us,webSocketServerEndpoint.getSession(u.getId()),null);
            });
        }
    }

    /**
     * 周六清除消息任务提醒
     */
    @Scheduled(cron = "59 59 23 ? * SAT")
    public void resetMes(){
        mesService.update(new UpdateWrapper<TzMes>().set("state","1").eq("type","1"));
    }
}
